package com.cmcc.groupcontacts;

import java.util.ArrayList;
import java.util.Date;

import android.app.Application;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.graphics.PixelFormat;
import android.location.Location;
import android.net.ConnectivityManager;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.android.application.WkaUncaughtException;
import com.baidu.mapapi.SDKInitializer;
import com.cmcc.groupcontacts.common.Const;
import com.cmcc.groupcontacts.common.CoreService;
import com.cmcc.groupcontacts.util.DisplayMetricsConverter;
import com.listener.AccountConflictMonitor;
import com.listener.NetStateReceiver;
import com.littlec.sdk.manager.CMIMHelper;
import com.yinhai.activity.R;
import com.yinhai.map.ServiceMap;
import com.yinhai.util.UuId;

/**
 * 应用程序入口
 * 
 * @author
 * 
 */
public class MainApp extends Application {
	private static final String LOG_TAG = "MainApp";

	public static MainApp instance; // 主应用对象实例

	private static DisplayMetricsConverter dmConverter = null; // 显示尺寸转换器
	private static SharedPreferences preference = null; // 配置文件读取器
	private static InputMethodManager imeManager = null; // 输入法

	private static ArrayList<AfterBlockedCallbackEvent> callCallbackEvents; // 来电拦截后回调事件集合
	private static ArrayList<AfterBlockedCallbackEvent> smsCallbackEvents; // 短信拦截后回调事件集合

	public static String blockedNumber; // 暂存CallReceiver拦截的号码，用于传递到CallLogObserver处理
	public static int blockedType; // 暂存CallReceiver拦截的类型，用于传递到CallLogObserver处理

	// 百度地图API相关
	// public BMapManager mBMapMan = null;
	public Location mLocation;
	public Date locationTime;
	// 来电提示
	public WindowManager wm;
	public View windowView;
	private WindowManager.LayoutParams params;
	private float mTouchStartX;
	private float mTouchStartY;
	private float x;
	private float y;
	public static int isIMConnecteStatus = 0;// IM登录状态 0:未登录 ；1：正在登录；2：登录成功；3：登录失败；4：帐号冲突
	//public static int isIMVOIPConnecteStatus = 0;//VOIP登录状态
	public static String IM_APPKEY = "115000aa";
	public boolean isRinging;

	public NetStateReceiver mNetStateReceiver;
	private AccountConflictMonitor mAccountConflictMonitor = null;

	public static Context getContext() {
		return instance.getApplicationContext();
	}

	public static ContextWrapper getContextWrapper() {
		return (ContextWrapper) instance;
	}

	public static DisplayMetricsConverter getDmConverter() {
		if (dmConverter == null) {
			dmConverter = new DisplayMetricsConverter(instance);
		}
		return dmConverter;
	}

	public static SharedPreferences getPreference() {
		if (preference == null) {
			preference = instance.getSharedPreferences(Const.APP_SETTING_FILE,
					Context.MODE_PRIVATE);
		}
		return preference;
	}

	public static ColorStateList getColor(int resId) {
		return instance.getResources().getColorStateList(resId);
	}

	/**
	 * 获取输入法管理器
	 * 
	 * @return
	 */
	public static InputMethodManager getIMEManager() {
		if (imeManager == null) {
			imeManager = (InputMethodManager) instance
					.getSystemService(INPUT_METHOD_SERVICE);
		}
		return imeManager;
	}

	/**
	 * 显示输入法
	 * 
	 * @param v
	 */
	public static void showIME(View v) {
		getIMEManager().showSoftInput(v,
				InputMethodManager.RESULT_UNCHANGED_SHOWN);
	}

	/**
	 * 隐藏输入法
	 * 
	 * @param binder
	 */
	public static void hideIME(IBinder binder) {
		getIMEManager().hideSoftInputFromWindow(binder,
				InputMethodManager.RESULT_UNCHANGED_SHOWN);
	}

	/**
	 * 获取来电拦截后回调事件集合
	 * 
	 * @return
	 */
	public static ArrayList<AfterBlockedCallbackEvent> getCallCallbackEvents() {
		return callCallbackEvents;
	}

	/**
	 * 获取信息拦截后回调事件集合
	 * 
	 * @return
	 */
	public static ArrayList<AfterBlockedCallbackEvent> getSmsCallbackEvents() {
		return smsCallbackEvents;
	}

	@Override
	public void onCreate() {
		Log.v(LOG_TAG, "主应用启动");
		super.onCreate();
		//初始化地图
		SDKInitializer.initialize(this);

		WkaUncaughtException uncaughtException = new WkaUncaughtException();
		Thread.setDefaultUncaughtExceptionHandler(uncaughtException);

		instance = this;
		callCallbackEvents = new ArrayList<AfterBlockedCallbackEvent>();
		smsCallbackEvents = new ArrayList<AfterBlockedCallbackEvent>();
		startCoreService();
		CMIMHelper.getCmAccountManager().init(getApplicationContext(),
				IM_APPKEY);

		if (mNetStateReceiver != null) {
			unregisterReceiver(mNetStateReceiver);// 否则每次退出登录就会多弹出连网或断网连接
			mNetStateReceiver.destroy(); // 因为账号冲突退出后，电话重新登录网络监听器仍有效
			mNetStateReceiver = null;
		}
		IntentFilter filter = new IntentFilter();
		filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		mNetStateReceiver = new NetStateReceiver();
		registerReceiver(mNetStateReceiver, filter);
		if(mAccountConflictMonitor != null) {
			mAccountConflictMonitor.destroy();
			mAccountConflictMonitor = null;
		}
		mAccountConflictMonitor = new AccountConflictMonitor();
	}

	public NetStateReceiver getmNetStateReceiver() {
		return mNetStateReceiver;
	}

	/**
	 * 启动核心服务
	 */
	public void startCoreService() {
		if (!CoreService.isRunning) {
			Log.v(LOG_TAG, "主应用启动核心服务");
			Intent intent1 = new Intent(this, CoreService.class);
			ServiceMap.getMap().put(UuId.getUUID(), intent1);
			startService(intent1);
		}
	}

	/**
	 * 该事件不一定会在注销期调用
	 */
	@Override
	public void onTerminate() {
		Log.v(LOG_TAG, "主应用销毁");
		super.onTerminate();

		instance = null;
	}

	// ========== events ==========

	/**
	 * 来电或信息拦截后的回调事件
	 */
	public interface AfterBlockedCallbackEvent {
		void invoke(Message msg);
	}

	public void initWindowManager() {
		if (wm != null) {
			return;
		}
		mTouchStartX = 0;
		mTouchStartY = 0;
		x = 0;
		y = 0;
		wm = (WindowManager) getApplicationContext().getSystemService(
				Context.WINDOW_SERVICE);
		params = new WindowManager.LayoutParams();
		params.type = WindowManager.LayoutParams.TYPE_PHONE;
		params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
				| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
		params.gravity = Gravity.TOP;
		params.x = 0;
		params.y = 0;
		params.width = WindowManager.LayoutParams.WRAP_CONTENT;
		params.height = 300;
		params.format = PixelFormat.RGBA_8888;
		windowView = LayoutInflater.from(getApplicationContext()).inflate(
				R.layout.window_call, null);
		windowView.findViewById(R.id.btn_close).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						try {
							if (wm != null && windowView != null) {
								wm.removeViewImmediate(windowView);
								wm = null;
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
		windowView.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					// 获取相对View的坐标，即以此View左上角为原点
					mTouchStartX = event.getRawX();
					mTouchStartY = event.getRawY();
					x = params.x;
					y = params.y;
					break;
				case MotionEvent.ACTION_MOVE:
					params.x = (int) (x + event.getRawX() - mTouchStartX);
					params.y = (int) (y + (int) event.getRawY() - mTouchStartY);
					updateViewPosition(params);
					break;

				case MotionEvent.ACTION_UP:
					mTouchStartX = mTouchStartY = 0;
					break;
				}
				return true;

			}
		});
		wm.addView(windowView, params);
	}

	private void updateViewPosition(WindowManager.LayoutParams wmParams) {
		// 更新浮动窗口位置参数
		wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
		wmParams.height = 300;
		wm.updateViewLayout(windowView, wmParams);
	}
	public AccountConflictMonitor getAccountConflictMonitor(){
		return this.mAccountConflictMonitor;
	}
}
